﻿using System;
using System.Collections.Generic;
using System.Text;
using Oragon.Architecture.Data.SqlBuilder.Operators;
using System.Xml.Serialization;

namespace Oragon.Architecture.Data.SqlBuilder
{
	[Serializable]
	public enum LogicOperator
	{
		And,
		Or
	}

	/// <summary>
	/// Representa a clausula where de um SQL Stetement
	/// </summary>
	[Serializable]
	public class WhereClause : ISQLStatement
	{
		public WhereClause()
		{
			this.DefaultOperator = LogicOperator.And;
			this.Items = new List<SQLOperator>();
		}

		public LogicOperator DefaultOperator { get; set; }

		public List<SQLOperator> Items { get; set; }

		public string ToSQL()
		{
			System.IO.StringWriter SQL = new System.IO.StringWriter(System.Globalization.CultureInfo.InvariantCulture);
			if (this.Items.Count > 0)
			{
				SQL.WriteLine("WHERE ");
				for (int itemIntex = 0; itemIntex < this.Items.Count; itemIntex++)
				{
					SQLOperator currentOperator = this.Items[itemIntex];
					if ((currentOperator is AndUnaryOperator) || (currentOperator is OrUnaryOperator))
					{
						if (itemIntex == 0)
						{
							SQL.WriteLine("\t"+((UnaryOperator)currentOperator).Expression.ToSQL());
						}
						else
						{
							SQL.WriteLine("\t" + currentOperator.ToSQL());
						}

					}
					else
					{
						if (itemIntex == 0)
						{
							SQL.WriteLine("\t" + currentOperator.ToSQL());
							//SQL.WriteLine("	{1}{0}", , (itemIntex != 0) ? this.Operator.ToString() : string.Empty);
						}
						else
						{
							if (this.DefaultOperator == LogicOperator.And)
								SQL.WriteLine("\t" + new AndUnaryOperator(currentOperator).ToSQL());
							else if (this.DefaultOperator == LogicOperator.Or)
								SQL.WriteLine("\t" + new OrUnaryOperator(currentOperator).ToSQL());
						}
					}
				}
			}

			return SQL.ToString();
		}

	}
}
